package bar.dark.lee.setting.auto;

import java.util.ArrayList;
import java.util.List;

import bar.dark.lee.BDConstents;
import bar.dark.lee.IntroActivitiy;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import bar.dark.lee.setting.category.CategoryAdapter;
import bar.dark.lee.setting.category.CategoryInActivity;
import bar.dark.lee.setting.data.DataInActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AutoActivity extends SuperActivity
{
	public static final String AUTO_DATA = "auto_data";
	
	public static final String AUTO_UPDATE_DELECT_FLAG = "auto_update_delete_flag";
	public static final int AUTO_UPDATE = 0;
	public static final int AUTO_INSERT = 1;

	private static final int REQUEST_INSERT = 0;

	private DBSQLite sql;
	
	private RadioButton radioNo;
	private RadioButton radioOk;
	private RadioButton radioEx;
	
	private ListView listView;
	
	private View resultView;
	
	private Button insertButton;
	private Button saveButton;
	
	private ArrayList<AutoData> autoList;
	
	private int autoSetting;
	
	private int introFlag = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		isAdFlag = false;
		
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.auto_activity);
		
		setTitle("통장/신용카드 자동화");
		
		setFindView();
		setOnClickListener();
		
		introFlag = 0;
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(0);
	}
	
	@Override
	public void onBackPressed()
	{
		if (introFlag != 0)
		{
			BDUtil.showDialogOK(this, "알림", 
					"통장/신용카드 자동화 내역 입력을 위해 초기 화면으로 이동합니다.", 
					new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					BDUtil.btnEnable = true;
					BDUtil.asyncFlag = 0;
					
					Intent intent = new Intent(superContext, IntroActivitiy.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(intent);
				}
			});
		}
		else
		{
			super.onBackPressed();
		}
	}

	private void setFindView()
	{
		radioNo = (RadioButton) findViewById(R.id.autoRadioNo);
		radioOk = (RadioButton) findViewById(R.id.autoRadioOk);
		radioEx = (RadioButton) findViewById(R.id.autoRadioEx);
		listView = (ListView) findViewById(R.id.autoListView);
		
		insertButton = (Button) findViewById(R.id.autoInsertButton);
		saveButton = (Button) findViewById(R.id.autoSaveButton);
		
		LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		resultView = li.inflate(R.layout.view_no_result, null);
	}
	private void setOnClickListener()
	{
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(AutoActivity.this, AutoInsertActivity.class);
				intent.putExtra(AUTO_UPDATE_DELECT_FLAG, AUTO_INSERT);
				startActivityForResult(intent, REQUEST_INSERT);
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (radioNo.isChecked())
				{
					BDUtil.showSelectDialog(AutoActivity.this, "알림", 
							"안함으로 변경 하실 경우 \n할부 내역이 정상적으로 적용되지 않습니다. 계속하시겠습니까?", 
							new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							new ShowDialog().execute(1);
						}
					}, new DialogInterface.OnClickListener()
					{
						
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.dismiss();
						}
					});
				}
				else
				{
					new ShowDialog().execute(1);
				}
			}
		});
	}
	
	private void setSaveData()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		
		if (radioNo.isChecked())
		{
			editor.putInt(BDConstents.AUTO_SETTING, 0);
		}
		else if (radioOk.isChecked())
		{
			editor.putInt(BDConstents.AUTO_SETTING, 1);
		}
		else if (radioEx.isChecked())
		{
			editor.putInt(BDConstents.AUTO_SETTING, 2);
		}
		
		editor.commit();
	}
	
	private void setData()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		autoSetting = pref.getInt(BDConstents.AUTO_SETTING, 0);
		
		sql.selectMapTile(this, "SELECT * FROM auto_bank ORDER BY autodate ASC;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				autoList = new ArrayList<AutoData>();
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int categoryIdx = c.getColumnIndex("category");
				int moneyIdx = c.getColumnIndex("money");
				int moneytypeIdx = c.getColumnIndex("moneytype");
				int autodateIdx = c.getColumnIndex("autodate");
				int signdateIdx = c.getColumnIndex("signdate");
				int moneykindIdx = c.getColumnIndex("moneykind");
				int memoIdx = c.getColumnIndex("memo");
				int kindIdx = c.getColumnIndex("kind");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					AutoData data = new AutoData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIdx));
					data.setCategory(c.getString(categoryIdx));
					data.setMoney(c.getString(moneyIdx));
					data.setMoneytype(c.getInt(moneytypeIdx) + "");
					data.setAutodate(c.getInt(autodateIdx)+ "");
					data.setSigndate(c.getInt(signdateIdx)+ "");
					data.setMoneykind(c.getString(moneykindIdx));
					data.setMemo(c.getString(memoIdx));
					data.setKind(c.getInt(kindIdx) + "");
					
					autoList.add(data);
					
					c.moveToNext();
				}
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Activity.RESULT_OK)
		{
			if (requestCode == REQUEST_INSERT)
			{
				boolean flag = data.getBooleanExtra(AutoInsertActivity.TODAY_INTRO, false);
				
				if (flag)
				{
					introFlag = 1;
				}
				else
				{
					introFlag = 0;
				}
			}
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			AutoData data = autoList.get(position);
			
			Intent intent = new Intent(AutoActivity.this, AutoSelectActivity.class);
			intent.putExtra(AUTO_DATA, data);
			startActivity(intent);
		}
	};
	
	public class AutoAdapter extends ArrayAdapter<AutoData>
	{
		private ArrayList<AutoData> list;

		public AutoAdapter(Context context, int textViewResourceId,
				ArrayList<AutoData> list)
		{
			super(context, textViewResourceId, list);
			this.list = list;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_auto, null);
			}
			
			AutoData data = list.get(position);
			
			TextView date = (TextView) v.findViewById(R.id.autoListItemDate);
			TextView name = (TextView) v.findViewById(R.id.autoListItemName);
			TextView kind = (TextView) v.findViewById(R.id.autolistItemKind);
			
			date.setText(data.getAutodate() + " 일");
			name.setText(data.getName());
			kind.setText(data.getMoneykind());
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(AutoActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			else if (arg0[0] == 1)
			{
				try
				{
					sql.beginTansaction(superContext);
					
					setSaveData();
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) 
					{
						return -1;
					}
				}
				
				return 1;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0)
			{
				if (autoSetting == 0)
				{
					radioNo.setChecked(true);
					radioOk.setChecked(false);
					radioEx.setChecked(false);
				}
				else if (autoSetting == 1)
				{
					radioNo.setChecked(false);
					radioOk.setChecked(true);
					radioEx.setChecked(false);
				}
				else if (autoSetting == 2)
				{
					radioNo.setChecked(false);
					radioOk.setChecked(false);
					radioEx.setChecked(true);
				}
				
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (autoList.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
					listView.setOnItemClickListener(null);
				}
				else
				{
					listView.setOnItemClickListener(onItemClickListener);
				}
				
				AutoAdapter adapter = new AutoAdapter(AutoActivity.this, R.layout.list_item_auto, autoList);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
			else if (result == 1)
			{
				BDUtil.showDialogOK(superContext, "알림", 
						"통장 자동화 선택 설정이 저장 되었습니다. 설정 적용을 위해 초기 화면으로 이동 됩니다.", new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						BDUtil.btnEnable = true;
						BDUtil.asyncFlag = 0;
						
						Intent intent = new Intent(superContext, IntroActivitiy.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
						startActivity(intent);
					}
				});
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(AutoActivity.this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_AUTOBANK);
		startActivity(intent);
	}
}
